An exception is an event that disrupts the normal flow of a program at runtime. Think of it as a "warning light" that signals something went wrong, allowing the program to handle it gracefully instead of crashing.
Exceptions are like "speed bumps" in your code. They slow down or stop execution unless you handle them properly!
Imagine you're cooking:
In Java, dividing by zero triggers an ArithmeticException that you handle similarly.
int a = 10;
int b = 0;
int result = a / b; // β Throws ArithmeticException: divide by zero
Q: What happens if an exception is not caught?
A: The program terminates, and the JVM prints the stack trace. Try running the above code to see!
The Throwable
class is the root of Javaβs exception hierarchy. All exceptions and errors inherit from it, like the "trunk" of a family tree.
Fallback Text Diagram (if image fails):
Throwable βββ Exception β βββ Checked Exceptions (e.g., IOException, SQLException) β βββ RuntimeException (Unchecked, e.g., NullPointerException) βββ Error (e.g., OutOfMemoryError, StackOverflowError)
π§ Mnemonic: Checked exceptions are like "boarding passes" β you must show (handle/declare) them before compiling.
try-catch
or declared with throws
.IOException
, SQLException
, FileNotFoundException
.π§ Mnemonic: Unchecked exceptions are like "pop quizzes" β they surprise you at runtime.
NullPointerException
, ArithmeticException
, ArrayIndexOutOfBoundsException
.π§ Mnemonic: Errors are like "server crashes" β too severe to fix in code.
StackOverflowError
: Infinite recursion.OutOfMemoryError
: No heap space.VirtualMachineError
: JVM issues.Q: Is IOException
checked or unchecked?
A: Checked β must be handled or declared.
The backbone of exception handling: try
for risky code, catch
for handling errors, finally
for cleanup.
Fallback Text Diagram (if image fails):
[Start] β [Try: Risky Code] βββ Exception β [Catch: Handle It] βββ [Finally: Cleanup] [End]
try {
// Risky code
} catch (ExceptionType e) {
// Handle exception
} finally {
// Cleanup (always runs)
}
try {
int result = 10 / 0; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} finally {
System.out.println("Cleanup done!");
}
π Output:
Cannot divide by zero!
Cleanup done!
π§ Mnemonic: Try = Test drive, Catch = Fix flat tire, Finally = Return car keys.
Q: Does finally
execute if System.exit()
is called?
A: No, itβs skipped on JVM shutdown.
Key for controlling exceptions manually or warning about them.
Fallback Text Diagram (if image fails):
throw: Actively throws an exception object throws: Declares possible exceptions in method signature
π§ Easy Explanation:
throw
: "Iβm throwing this error now!" (Action).throws
: "Heads up, this method might throw errors!" (Warning).Keyword | Meaning | Used In | Exceptions |
---|---|---|---|
throw |
Manually throw | Method body | One at a time |
throws |
Declare | Method signature | Multiple |
void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Underage!");
}
}
void readFile() throws IOException {
FileReader fr = new FileReader("file.txt");
}
π§ Mnemonic: Throw = Toss the ball, Throws = Warn others to catch it.
Q: Can throws
list unchecked exceptions?
A: Yes, but itβs optional since theyβre not enforced by the compiler.
Create tailored exceptions for specific scenarios, extending Exception
(checked) or RuntimeException
(unchecked).
π§ Mnemonic: Custom exceptions are like "customized warning signs" for your appβs unique issues.
class InvalidAgeException extends Exception {
InvalidAgeException(String msg) {
super(msg);
}
}
void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age too low!");
}
}
Q: Should custom exceptions extend Exception or RuntimeException?
A: Depends: Exception
for checked, RuntimeException
for unchecked.
These sound similar but are distinct β a favorite interview topic!
Fallback Text Diagram (if image fails):
final: Locks variables, methods, or classes finally: Cleanup block after try-catch finalize(): GC cleanup (deprecated)
π§ Easy Explanation:
final
: Makes things unchangeable (like sealing a contract).finally
: Always runs for cleanup (like locking the door).finalize()
: Called by GC before object destruction (avoid β deprecated).Keyword | Usage | Where | Note |
---|---|---|---|
final |
Prevent changes | Variables, Methods, Classes | Constants, no override/extend |
finally |
Cleanup | After try-catch | Always runs |
finalize() |
GC cleanup | Method | Deprecated (Java 9+) |
final int MAX_AGE = 100; // Constant
// MAX_AGE = 200; // β Error
β οΈ Avoid finalize()
β use try-with-resources
for cleanup!
Q: Can a final
class be extended?
A: No, itβs locked from inheritance.
Introduced in Java 7, automatically closes resources implementing AutoCloseable
.
π§ Mnemonic: Like a "self-cleaning" kitchen β resources close themselves.
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
// Use br
} catch (IOException e) {
e.printStackTrace();
} // br auto-closed
Q: What happens if a resource in try-with-resources throws an exception?
A: Itβs still closed, and the exception is caught or propagated.
Concept | Key Notes |
---|---|
Throwable | Root: Exception (checked/unchecked), Error |
Checked Exception | Compile-time; must handle/declare |
Unchecked | Runtime; optional to handle |
throw | Manually throw exception |
throws | Declare in signature |
finally | Always executes |
finalize() | GC cleanup (deprecated) |
try-with-resources | Auto-close resources |
Commonly asked in companies like Google, Amazon, Microsoft, etc.
A: Checked: Compile-time, must handle/declare (e.g., IOException
). Unchecked: Runtime, optional (e.g., NullPointerException
).
A: Throwable
β Exception
(Checked: IOException
, Unchecked: RuntimeException
) & Error
(OutOfMemoryError
). See hierarchy diagram above.
A: Yes, with finally
or in try-with-resources
.
A: It propagates up the call stack; if unhandled, JVM terminates with stack trace.
A: Rarely β they indicate severe issues (e.g., OutOfMemoryError
).
A: Calls close()
in a hidden finally
block.
A: final
: Locks variables/methods/classes. finally
: Cleanup block. finalize()
: Deprecated GC method.
A: For domain-specific errors to improve code clarity.
A: Yes, specific (subclass) to general (superclass) order.
A: Unhandled exceptions move up the call stack to be handled or crash the program.